<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/5/31
 * Time: 14:51
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Common\Business;

use App\Common\Lib\Log\Log;
use App\Exception\FooException;
use App\Model\GoodsCategoriesInfo;

class GoodsCategoriesInfoBusiness extends BusBase
{
    protected $obj_model;

    public function __construct()
    {
        $this->obj_model = new GoodsCategoriesInfo();
    }

    /**
     * @param array $arr
     * @param int $goods_id
     * @return true
     */
    public function setGoodsCategoriesList(array $arr = [], int $goods_id = 0)
    {
        if (empty($arr) || $goods_id == 0) {
            throw new FooException("数据错误");
        }
        //删除所有相关的数据
        try {
            $this->obj_model
                ->where('goods_id', $goods_id)
                ->forceDelete();
            //插入多条数据
            $insert_data = [];
            foreach ($arr as $v) {
                $insert_data[] = [
                    'goods_id' => $goods_id,
                    'category_id' => $v['category_id']
                ];
            }
            $res = $this->obj_model->insert($insert_data);
        } catch (\Exception $e) {
            Log::get('categoriesInfo-del', 'error')->error($e->getMessage());
            throw new FooException("操作失败");
        }
        if (!$res) {
            throw new FooException("操作失败");
        }
        return true;
    }
}